/**
 * Created by hylin on  2014/7/31.
 */
var fence = function () {
    var map = null,
        circle = null,
        slider = null,
        fenceData = {},
        minRadius = 200,
        maxRadius = 5000,
        fenceRadius = minRadius,
        params = goome.wx.utils.params(),
        $phoneSetMenu = $('.header .title .toolbox'),
        $phoneSetMask = $('#phone-set-mask'),
        $phone = $('#phone'),
        $deviceName = $('#device-name'),
        $radiusSlider = $('.radius-slider'),
        $currentRadius = $('#current-radius'),
        $sliderWrapper = $('.slider-wrapper'),
        $block = $('.block',$sliderWrapper),
        $passLine = $('.pass-line', $sliderWrapper),
        $originalBtn = $('#original-btn'),
        $setFence = $('#set-fence'),
        $switchFence = $('#switch-fence'),
        headerHeight = $('.header').height(),
        $crossContainer = $('#cross-container'),
        $contentContainer = $('#content-container');

    function getFenceData(){
        params.method = 'get';
        $.ajax({
            url: goome.wx.config.apiUrl+'tool/efence',
            data: params,
            dataType: 'jsonp',
            success: function(results){
                if(results && results.errcode === 0){
                    fenceData = results.data;
                    renderFence();
                }else{
                    goome.wx.utils.showTip(results.msg);
                }
            },
            error: function(err){
                goome.wx.utils.showTip(wxLang.getFenceFailed);
            }
        })
    }
    function renderFence(){
        if(fenceData.validate_flag == '1'){
            $setFence.removeClass('disabled').removeAttr('disabled');
            $switchFence.val(wxLang.closeFence).data('disabled', false);
        }else{
            $setFence.addClass('disabled').attr('disabled',true);
            $switchFence.val(wxLang.openFence).data('disabled', true);
        }
        $phone.val(fenceData.phone_num || '');
        if(fenceData.shape_type == '1') {
            var shape_param = fenceData.shape_param.split(','),
                point = new BMap.Point(shape_param[1],shape_param[0]);
            setRadius(+shape_param[2]);
            slider.setValue(+shape_param[2]);
            map.setCenter(point);
            circle.setCenter(point);
        }
    }
    function setFence(){
        params.method = 'set';
        params.validate_flag = '1';
        params.shape_type = '1';
        var center = map.getCenter();
        params.shape_param = center.lat+','+center.lng+','+fenceRadius;
        $.ajax({
            url: goome.wx.config.apiUrl + 'tool/efence',
            data: params,
            dataType: 'jsonp',
            success: function(results){
                if(results && results.errcode === 0){
                    goome.wx.utils.showTip(wxLang.setFenceSuccess);
                }else{
                    goome.wx.utils.showTip(results.msg);
                }
            },
            error: function(err){
                goome.wx.utils.showTip(wxLang.setFenceFailed);
            }
        });
    }
    function switchFence(flag){
        params.method = 'switch';
        params.validate_flag = flag?'1':'0';
        params.id = fenceData.id || '';
        var txt = flag?wxLang.on:wxLang.off;
        $.ajax({
            url: goome.wx.config.apiUrl + 'tool/efence',
            data: params,
            dataType: 'jsonp',
            success: function(results){
                if(results && results.errcode === 0){
                    $switchFence.val(flag?wxLang.closeFence:wxLang.openFence).data('disabled', !flag);
                    if(flag) {
                        $setFence.removeClass('disabled').removeAttr('disabled');
                    }else{
                        $setFence.addClass('disabled').attr('disabled', true);
                    }
                    goome.wx.utils.showTip(flag?wxLang.openFenceSuccess:wxLang.closeFenceSuccess);
                }else{
                    goome.wx.utils.showTip(results.msg);
                }
            },
            error: function(err){
                goome.wx.utils.showTip(flag?wxLang.openFenceFailed:wxLang.closeFenceFailed);
            }
        });
    }
    function renderMap() {
        var point = new BMap.Point(params.lng, params.lat);
        circle = new BMap.Circle(point, 200, {
            strokeColor: '#4E6BB9',
            fillColor: '#4E6BB9',
            strokeWeight: 2,
            strokeOpacity: 0.8,
            fillOpacity: 0.3
        });
        map.addOverlay(circle);
        map.addEventListener('dragend', function(e){
            setTimeout(function(){
                circle.setCenter(map.getCenter());
            }, 10);
        });
        map.addEventListener('zoomend', function(e){
            setTimeout(function(){
                circle.setCenter(map.getCenter());
            }, 10);
        });
    }

    function resize() {
        var h = $(window).height()-headerHeight;
        $contentContainer.height(h);
        $crossContainer.height(h);
    }

    function initMap() {
        var center = new BMap.Point(params.lng, params.lat);
        map = new BMap.Map('map-container');
        map.centerAndZoom(center, 16);
        map.addControl(new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_ZOOM,
            offset: new BMap.Size(0, 70)
        }));
        map.addControl(new BMap.ScaleControl({
            anchor: BMAP_ANCHOR_TOP_LEFT,
            offset: new BMap.Size(0, 70)
        }));
        map.enableScrollWheelZoom(true);
    }
    function setRadius(radius){
        if(typeof radius == 'string'){
            if(radius == 'less'){
                fenceRadius -= 100;
            }else if(radius == 'more'){
                fenceRadius += 100;
            }else{
                fenceRadius = +radius;
            }
        }else{
            fenceRadius = radius;
        }
        fenceRadius = fenceRadius < 200?200:fenceRadius;
        fenceRadius = fenceRadius > 5000? 5000:fenceRadius;
        circle.setRadius(fenceRadius);
        $currentRadius.text(fenceRadius);
        if(fenceRadius >= 4000){
            map.setZoom(12);
        }else if(fenceRadius >= 3000 && fenceRadius <= 4000){
            map.setZoom(13);
        }else if(fenceRadius >= 2000 && fenceRadius <= 3000){
            map.setZoom(14);
        }else if(fenceRadius >= 1000 && fenceRadius <= 2000){
            map.setZoom(15);
        }else{
            map.setZoom(16);
        }
    }
    function bindEvents(){
        $radiusSlider.on('click', '.button', function(e){
            var $this = $(this);
            var action = $this.data('action');
            setRadius(action);
            slider.setValue(fenceRadius);
        });
        $originalBtn.on('click', function(){
            var point = new BMap.Point(params.lng, params.lat);
            map.setCenter(point);
            circle.setCenter(point);
        });
        $setFence.on('click', function(){
            if($(this).data('disabled')){
                return false;
            }
            setFence();
        });
        $switchFence.on('click', function(){
            switchFence($(this).data('disabled'));
        });
        $phoneSetMenu.on('click', function(e){
            $deviceName.text(decodeURIComponent(params.name));
            $phoneSetMask.show();
            e.preventDefault();
        });
        $phoneSetMask.on('click', '.normal-btn', function(){
            var action = $(this).data('action');
            if(action == 'confirm'){
                params.method = 'saveAlarmPhoneNum';
                params.phone_num = $.trim($phone.val());
                params.time_zone = new Date().getTimezoneOffset();
                params.lang = 'zh-CN';
                params.id = fenceData.id || '';
                $.ajax({
                    url: goome.wx.config.apiUrl + 'tool/efence',
                    data: params,
                    dataType: 'jsonp',
                    success: function(results){
                        if(results && results.errcode === 0){
                            goome.wx.utils.showTip(wxLang.setSmsSuccess);
                            $phoneSetMask.hide();
                        }else{
                            goome.wx.utils.showTip(results.msg);
                        }
                    },
                    error: function(err){
                        goome.wx.utils.showTip(wxLang.setSmsFailed);
                    }
                });
            }else if(action == 'cancel'){
                $phoneSetMask.hide();
            }
        });
    }
    function init() {
        bindEvents();
        resize();
        initMap();
        renderMap();
        getFenceData();
        slider = new MobileRangeSlider($sliderWrapper[0], {
            min: 200,
            max: 5000,
            value: 200,
            change: function(value){
                setRadius(Math.round(value/100)*100);
            }
        });
    }

    return {
        init: init
    };
}();